package com.ahy231.shiro;

import com.ahy231.service.LoginService;
import com.ahy231.utils.JWTUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author ahy231
 * @date 2021/7/23 11:14
 * @description 自定义 Realm
 */
@Component
public class CustomRealm extends AuthorizingRealm {

    private final LoginService loginService;
    private final JWTUtil jwtUtil;

    public CustomRealm(LoginService loginService, JWTUtil jwtUtil) {
        this.loginService = loginService;
        this.jwtUtil = jwtUtil;
    }

    /**
     * 必须重写此方法，不然会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        Object credentials = token.getCredentials();
        Assert.isInstanceOf(String.class, credentials, "token 不是 String 类型");
        String credentialJwt = (String) credentials;
        Long userId = JWTUtil.getUserId(credentialJwt);
        if (userId == null || !jwtUtil.verify(credentialJwt, userId)) {
            throw new AuthenticationException("token 认证失败");
        }
        if (!loginService.isUserExisting(userId)) {
            throw new AuthenticationException("找不到 userId 为 " + userId + " 的用户");
        }
        return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), "MyRealm");
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Long userId = JWTUtil.getUserId(principals.toString());
        Assert.notNull(userId, "userId 为空");
        Set<String> roles = loginService.getRolesByUserId(userId);
        // 不设置权限
        authorizationInfo.setRoles(roles);
        return authorizationInfo;
    }
}
